package com.eorchis.module.dataSynchronization.ui.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.eorchis.core.ui.commond.ResultState;
import com.eorchis.module.dataSynchronization.bean.ClassScopeDept;
import com.eorchis.module.dataSynchronization.bean.ClassSignUpDept;
import com.eorchis.module.dataSynchronization.bean.Department;
import com.eorchis.module.dataSynchronization.bean.DepartmentUser;
import com.eorchis.module.dataSynchronization.bean.TrainingClass;
import com.eorchis.module.dataSynchronization.bean.TrainingClassUser;
import com.eorchis.module.dataSynchronization.bean.User;
import com.eorchis.module.dataSynchronization.bean.UserClassTypeHour;
import com.eorchis.module.dataSynchronization.service.ISynchroService;
import com.eorchis.module.util.EADZipUtil;
import com.eorchis.module.util.FileOperation;
import com.eorchis.module.util.ZipUtil;

@Controller("synchroController")
@RequestMapping(value = synchroController.MODULE_PATH)
public class synchroController {

	// 模块页面根路径
	public static final String MODULE_PATH = "/module/synchro";

	@Autowired
	@Qualifier("com.eorchis.module.dataSynchronization.service.impl.synchroServiceImpl")
	private ISynchroService synchroServiceImpl;
	/**
	 * 接收学员学时数据
	 * 
	 * @param
	 * @return
	 * @throws Exception
	 * @author RongSL 2018年1月19日
	 */
	@RequestMapping("/importDataSynchronization")
	public String importDataSynchronization(HttpServletRequest request, HttpServletResponse response, @ModelAttribute("resultState") ResultState resultState) {
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
			for (MultipartFile multipartFile : fileMap.values()) {
				CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) multipartFile;
				FileItem item = commonsMultipartFile.getFileItem();
				// 在服务器端创建文件夹
				String serverPath = request.getSession().getServletContext().getRealPath(File.separator);
				serverPath += "userHour" + File.separator;
				File file = new File(serverPath);
				if (!file.exists()) {
					file.mkdir();
				}
				// 将文件写入到本地
				file = new File(serverPath + "userHour.zip");
				item.write(file);
				// 解压文件
				EADZipUtil.unzip(serverPath + "userHour.zip", serverPath, "GoldGov");
				// 依次读取文件
				BufferedReader in;
				String pathText;
				String temp = "";// 临时缓存 保存读取到的每一行记录
				String result = "";// 取出所有数据
				pathText = new String((serverPath + "userHour" + File.separator + "user.txt").getBytes(), "UTF-8");
				in = new BufferedReader(new FileReader(pathText));
				result = "";
				while ((temp = in.readLine()) != null) {
					result = result + temp;
				}
				// 关闭流
				in.close();
				List<User> user = JSONObject.parseArray(result, User.class);
				for(User u:user){
					if (synchroServiceImpl.judgeUser(u.getUserID()))
						synchroServiceImpl.updateUser(u);
					else
						synchroServiceImpl.addUser(u);
				}
				
				pathText = new String((serverPath + "userHour" + File.separator + "dep.txt").getBytes(), "UTF-8");
				in = new BufferedReader(new FileReader(pathText));
				result = "";
				while ((temp = in.readLine()) != null) {
					result = result + temp;
				}
				// 关闭流
				in.close();
				List<Department> dep = JSONObject.parseArray(result, Department.class);
				for(Department d:dep){
					if (synchroServiceImpl.judgeDepartment(d.getDepID()))
						synchroServiceImpl.updateDepartment(d);
					else
						synchroServiceImpl.addDepartment(d);
				}

				pathText = new String((serverPath + "userHour" + File.separator + "depUser.txt").getBytes(), "UTF-8");
				in = new BufferedReader(new FileReader(pathText));
				result = "";
				while ((temp = in.readLine()) != null) {
					result = result + temp;
				}
				// 关闭流
				in.close();
				List<DepartmentUser> depUser = JSONObject.parseArray(result, DepartmentUser.class);
				for(DepartmentUser du:depUser){
					if (synchroServiceImpl.judgeDepartmentUser(du.getDepuserID()))
						synchroServiceImpl.updateDepartmentUser(du);
					else
						synchroServiceImpl.addDepartmentUser(du);
				}
				
				pathText = new String((serverPath + "userHour" + File.separator + "trainingClassPxf.txt").getBytes(), "UTF-8");
				in = new BufferedReader(new FileReader(pathText));
				result = "";
				while ((temp = in.readLine()) != null) {
					result = result + temp;
				}
				// 关闭流
				in.close();
				List<TrainingClass> trainingClassPxf = JSONObject.parseArray(result, TrainingClass.class);
				for(TrainingClass c:trainingClassPxf){
					if (synchroServiceImpl.judgeTrainingClassPxf(c.getClassID()))
						synchroServiceImpl.updateTrainingClassPxf(c);
					else
						synchroServiceImpl.addTrainingClassPxf(c);
					synchroServiceImpl.cleanClassScopeDept(c.getClassID());
					synchroServiceImpl.cleanClassSignUpDept(c.getClassID());
				}

				pathText = new String((serverPath + "userHour" + File.separator + "trainingClass.txt").getBytes(), "UTF-8");
				in = new BufferedReader(new FileReader(pathText));
				result = "";
				while ((temp = in.readLine()) != null) {
					result = result + temp;
				}
				// 关闭流
				in.close();
				List<TrainingClass> trainingClass = JSONObject.parseArray(result, TrainingClass.class);
				for(TrainingClass c:trainingClass){
					if (synchroServiceImpl.judgeTrainingClass(c.getClassID()))
						synchroServiceImpl.updateTrainingClass(c);
					else
						synchroServiceImpl.addTrainingClass(c);
				}
				
				pathText = new String((serverPath + "userHour" + File.separator + "annulUserPxf.txt").getBytes(), "UTF-8");
				in = new BufferedReader(new FileReader(pathText));
				result = "";
				while ((temp = in.readLine()) != null) {
					result = result + temp;
				}
				// 关闭流
				in.close();
				List<String> annulUserPxfIds = JSONObject.parseArray(result, String.class);
				synchroServiceImpl.deleteAnnulUserPxfByIds(annulUserPxfIds);

				pathText = new String((serverPath + "userHour" + File.separator + "annulUser.txt").getBytes(), "UTF-8");
				in = new BufferedReader(new FileReader(pathText));
				result = "";
				while ((temp = in.readLine()) != null) {
					result = result + temp;
				}
				// 关闭流
				in.close();
				List<String> annulUserIds = JSONObject.parseArray(result, String.class);
				synchroServiceImpl.deleteAnnulUserByIds(annulUserIds);
				
				pathText = new String((serverPath + "userHour" + File.separator + "trainingClassUserPxf.txt").getBytes(), "UTF-8");
				in = new BufferedReader(new FileReader(pathText));
				result = "";
				while ((temp = in.readLine()) != null) {
					result = result + temp;
				}
				// 关闭流
				in.close();
				List<TrainingClassUser> trainingClassUserPxf = JSONObject.parseArray(result, TrainingClassUser.class);
				for(TrainingClassUser cu:trainingClassUserPxf){
					if (synchroServiceImpl.judgeTrainingClassUserPxf(cu.getClassUserID()))
						synchroServiceImpl.updateTrainingClassUserPxf(cu);
					else
						synchroServiceImpl.addTrainingClassUserPxf(cu);
				}

				pathText = new String((serverPath + "userHour" + File.separator + "trainingClassUser.txt").getBytes(), "UTF-8");
				in = new BufferedReader(new FileReader(pathText));
				result = "";
				while ((temp = in.readLine()) != null) {
					result = result + temp;
				}
				// 关闭流
				in.close();
				List<TrainingClassUser> trainingClassUser = JSONObject.parseArray(result, TrainingClassUser.class);
				for(TrainingClassUser cu:trainingClassUser){
					if (synchroServiceImpl.judgeTrainingClassUser(cu.getClassUserID()))
						synchroServiceImpl.updateTrainingClassUser(cu);
					else
						synchroServiceImpl.addTrainingClassUser(cu);
				}

				pathText = new String((serverPath + "userHour" + File.separator + "userClassTypeHour.txt").getBytes(), "UTF-8");
				in = new BufferedReader(new FileReader(pathText));
				result = "";
				while ((temp = in.readLine()) != null) {
					result = result + temp;
				}
				// 关闭流
				in.close();
				List<UserClassTypeHour> userClassTypeHour = JSONObject.parseArray(result, UserClassTypeHour.class);
				for(UserClassTypeHour h:userClassTypeHour){
					if (synchroServiceImpl.judgeUserClassTypeHour(h.getID().toString()))
						synchroServiceImpl.updateUserClassTypeHour(h);
					else
						synchroServiceImpl.addUserClassTypeHour(h);
				}

				pathText = new String((serverPath + "userHour" + File.separator + "classScopeDept.txt").getBytes(), "UTF-8");
				in = new BufferedReader(new FileReader(pathText));
				result = "";
				while ((temp = in.readLine()) != null) {
					result = result + temp;
				}
				// 关闭流
				in.close();
				List<ClassScopeDept> csd = JSONObject.parseArray(result, ClassScopeDept.class);
				for(ClassScopeDept d:csd){
					/*if (synchroServiceImpl.judgeClassScopeDept(d.getScopeDeptId()))
						synchroServiceImpl.updateClassScopeDept(d);
					else*/
					synchroServiceImpl.addClassScopeDept(d);
				}

				pathText = new String((serverPath + "userHour" + File.separator + "classSignUpDept.txt").getBytes(), "UTF-8");
				in = new BufferedReader(new FileReader(pathText));
				result = "";
				while ((temp = in.readLine()) != null) {
					result = result + temp;
				}
				// 关闭流
				in.close();
				List<ClassSignUpDept> csud = JSONObject.parseArray(result, ClassSignUpDept.class);
				for(ClassSignUpDept d:csud){
					/*if (synchroServiceImpl.judgeClassSignUpDept(d.getSignUpDeptId()))
						synchroServiceImpl.updateClassSignUpDept(d);
					else*/
					synchroServiceImpl.addClassSignUpDept(d);
				}
				
				resultState.setState(ResultState.RESULT_STATE_SUCCESS);
				resultState.setMessage("导入成功");

				ZipUtil.deleteExcelPath(new File(serverPath));
			}
			// 数据开始同步

		} catch (Exception e) {
			resultState.setState(ResultState.RESULT_STATE_SUCCESS);
			resultState.setMessage("数据同步报错！");
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 导出班级学员信息
	 * @throws Exception
	 * @author LongJZ
	 * @date 2018-3-2
	 */
	@RequestMapping("/exportDataSynchronization")
	public void exportDataSynchronization(HttpServletRequest request, HttpServletResponse response) {
		try {
			Integer daysBefore = Integer.parseInt(request.getParameter("daysBefore") != null ? request.getParameter("daysBefore") : "0");
			// 在服务器端创建文件夹
			String serverPath = request.getSession().getServletContext().getRealPath(File.separator);
			serverPath += "classUser" + File.separator;
			File file = new File(serverPath);
			if (!file.exists()) {
				file.mkdir();
			}
			/*file = new File(new String((serverPath +"user.txt").getBytes(), "UTF-8"));
			FileOperation.createFile(file);
			FileOperation.writeTxtFile(JSON.toJSONString(synchroServiceImpl.findUserList(daysBefore)), file);*/
			file = new File(new String((serverPath +"trainingClass.txt").getBytes(), "UTF-8"));
			FileOperation.createFile(file);
			List<TrainingClass> classList = synchroServiceImpl.findTrainingClassList(daysBefore);
			FileOperation.writeTxtFile(JSON.toJSONString(classList), file);
			
			String classIds = "";
			for (TrainingClass c : classList) {
				classIds += "," + c.getClassID();
			}
			String[] classIdsArr = classIds.split(",");
			file = new File(new String((serverPath +"classScopeDept.txt").getBytes(), "UTF-8"));
			FileOperation.createFile(file);
			FileOperation.writeTxtFile(JSON.toJSONString(synchroServiceImpl.findClassScopeDeptList(classIdsArr)), file);
			file = new File(new String((serverPath +"classSignUpDept.txt").getBytes(), "UTF-8"));
			FileOperation.createFile(file);
			FileOperation.writeTxtFile(JSON.toJSONString(synchroServiceImpl.findClassSignUpDeptList(classIdsArr)), file);
			
			file = new File(new String((serverPath +"trainingClassUser.txt").getBytes(), "UTF-8"));
			FileOperation.createFile(file);
			FileOperation.writeTxtFile(JSON.toJSONString(synchroServiceImpl.findTrainingClassUserList(daysBefore)), file);
			
			file = new File(new String((serverPath +"annulUser.txt").getBytes(), "UTF-8"));
			FileOperation.createFile(file);
			FileOperation.writeTxtFile(JSON.toJSONString(synchroServiceImpl.findAnnulUserIds()), file);
			
			String path = request.getSession().getServletContext().getRealPath(File.separator)+System.currentTimeMillis() + File.separator;
			file=new File(path);
			synchroServiceImpl.cleanAnnulUser();
			if(!file.exists()){
				file.mkdir();
			}
			EADZipUtil.zip(serverPath, path+"classUser.zip", true, "GoldGov");
			// 弹出下载框供用户下载
			ZipUtil.downFile(response, path, "classUser.zip");
			// 删除生成文件夹，txt及ZIP
			ZipUtil.deleteExcelPath(new File(serverPath));
			ZipUtil.deleteExcelPath(new File(path));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
